package lanou.giftsay_01.tools;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

import lanou.giftsay_01.R;

/**
 * Created by dllo on 16/7/28.
 */
public class MyCircleimageView extends ImageView {

    private Paint mPanit;

    private boolean isCircle;

    public MyCircleimageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public MyCircleimageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
        //获取到自定义在attrs.xml中的属性
        TypedArray  array = context.obtainStyledAttributes(attrs, R.styleable.MyCircleimageView);
        isCircle = array.getBoolean(R.styleable.MyCircleimageView_isCircle, false);
    }

    public MyCircleimageView(Context context) {
        super(context);
        init();
    }

    public void init() {
        setLayerType(LAYER_TYPE_SOFTWARE, null);//关闭硬件优化
        mPanit = new Paint();
        mPanit.setAntiAlias(true);

    }

    @Override
    protected void onDraw(Canvas canvas) {


        if (isCircle) {

            //获取到xml布局中或者是setRecource()中设置的图片
            Drawable drawable = getDrawable();
            //设置我的图片的边界,让他充满画布,
            //getWidth() ,getHeight 获取到的canvas的宽高
            drawable.setBounds(0, 0, getWidth(), getHeight());
            //将图片绘制到画布上
            drawable.draw(canvas);
            // 重新创建一个画笔,防止两个画笔冲突
            Paint paint = new Paint();
            paint.setAntiAlias(true);
            //因为最后的交集出来的是图片,所以需要圆形的画布上绘制bitmap
            Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
            //新建一个可以画图片的一个圆形的画布
            Canvas canvas1 = new Canvas(bitmap);
            //画圆
            canvas1.drawCircle(getWidth() / 2, getHeight() / 2, getWidth() / 2, paint);
            //设置画笔的Xfer模式,显示交集,下层在上
            mPanit.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
            //最后将交集的bitmap绘制到界面
            canvas.drawBitmap(bitmap, 0, 0, mPanit);
        } else {
             super.onDraw(canvas);
        }
    }
}